package com.heisen.uua.service.login;

import com.heisen.security.entity.UuaUser;
import com.heisen.uua.service.AbstractCustomTokenGranter;
import com.heisen.uua.service.impl.XmUserDetailServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;
@Slf4j
public class WebPcLoginGranter  extends AbstractCustomTokenGranter {

    private XmUserDetailServiceImpl userService;


    private AuthenticationManager authenticationManager;

    public WebPcLoginGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory , XmUserDetailServiceImpl userService,AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, "password");
        this.userService = userService;
        this.authenticationManager=authenticationManager;
    }

    @Override
    protected UuaUser userLogin(Map<String, String> parameters) {
       // String grantType = parameters.get("grant_type");
        String username = parameters.get("username");
        String password = parameters.get("password");

        Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        userAuth = authenticationManager.authenticate(userAuth);
        return (UuaUser) userAuth.getPrincipal();
    }
}
